<template>
    <el-dialog :model-value="modifyDialogVisible" title="上传头像" :destroy-on-close="true" @close="closeDialog"
        width="600px">
        <div class="avatar-container">
            <div v-show="!options.img">
                <el-upload class="upload" ref="elUpload" action="#" :on-change="upload"
                    accept="image/png, image/jpeg, image/jpg" :show-file-list="false" :auto-upload="false">
                    <template v-slot:trigger>
                        <el-button type="primary" ref="uploadButton">选择图片</el-button>
                    </template>
                </el-upload>
                <div>支持jpg、png格式的图片，大小不超过5M</div>
            </div>
            <div v-show="options.img" class="avatar-crop">
                <vueCropper class="crop-box" ref="cropper" :img="options.img" :autoCrop="options.autoCrop"
                    :outputSize="options.outputSize" :outputType="options.outputType" :fixedBox="options.fixedBox"
                    :canMoveBox="options.canMoveBox" :autoCropWidth="options.autoCropWidth"
                    :autoCropHeight="options.autoCropHeight" :centerBox="options.centerBox" :fixed="options.fixed"
                    :fixedNumber="options.fixedNumber" :canMove="options.canMove" :canScale="options.canScale" />
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <div class="reupload" @click="reupload">
                    <span v-show="options.img">重新上传</span>
                </div>
                <div>
                    <el-button type="primary" @click="getCrop">确 定</el-button>
                </div>
            </span>
        </template>
    </el-dialog>
</template>


<script setup>
import { ref, reactive } from 'vue'

import 'vue-cropper/dist/index.css'
import { VueCropper } from "vue-cropper"

import { ElMessage } from 'element-plus'
import { modifyAvatarAPI } from '@/apis/user';
import { useUserStore } from '@/stores/user';

const modifyDialogVisible = ref(false)
const emits = defineEmits(['update:modelValue'])

function closeDialog() { // 子传父
    options.img = ""
    emits("update:modelValue", false);
}

const cropper = ref()
const uploadButton = ref()

// vueCropper组件 裁剪配置信息
const options = reactive({
    img: "", // 原图
    autoCrop: true, // 默认生成截图框
    outputSize: 1, // 裁剪生成图片的质量
    outputType: 'jpg', // 裁剪生成图片的格式
    fixedBox: false, // 固定截图框大小
    canMoveBox: true, // 截图框可以拖动
    autoCropWidth: 250, // 截图框宽度
    autoCropHeight: 250, // 截图框高度
    fixed: true, // 截图框宽高固定比例
    fixedNumber: [1, 1], // 截图框的宽高比例
    centerBox: true, // 截图框被限制在图片里面
    canMove: false, // 上传图片不允许拖动
    canScale: false // 上传图片不允许滚轮缩放
})

const upload = (file) => {
    const isIMAGE = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
    const isLt5M = file.raw.size / 1024 / 1024 < 5
    if (!isIMAGE) {
        ElMessage.warning("请选择 jpg、png 格式的图片");
        return false
    }
    if (!isLt5M) {
        ElMessage.warning("图片大小不能超过 5MB");
        return false
    }
    let reader = new FileReader()

    reader.readAsDataURL(file.raw)
    //console.log(reader);

    reader.onload = e => {
        options.img = e.target.result // base64
    }
}

// 重新上传
const reupload = () => {
    uploadButton.value.ref.click()
}

// 获取截图信息
const getCrop = () => {
    // 获取图片二进制数据
    cropper.value.getCropBlob((data) => {
        let formData = new FormData()
        formData.append("avatar", data)
        modifyAvatarAPI(formData).then((res) => {
            if (res.code === 0) {
                // 请求成功
                console.log("请求成功")
                useUserStore().userInfo.avatarUrl = res.avatarUrl
                // 刷新图片缓存
                closeDialog()
                window.location.reload();
            }
        })
    })
}
</script>

<style scoped lang="scss">
.dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;

    .reupload {
        color: #409eff;
        cursor: pointer;
    }
}

.avatar-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 560px;
    height: 350px;
    background-color: #f0f2f5;
    margin-right: 10px;
    border-radius: 4px;

    .upload {
        text-align: center;
        margin-bottom: 24px;
    }

    .avatar-crop {
        width: 560px;
        height: 350px;
        position: relative;

        .crop-box {
            width: 100%;
            height: 100%;
            border-radius: 4px;
            overflow: hidden;
        }
    }
}
</style>